    //
//  FirstViewController.m
//  DogLocate
//
//  Created by mac on 11-5-5.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "FirstViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "DogLocateAppDelegate.h"
#import "SecondViewController.h"
#import "extev.h"
#import "Coordinate.h"

int timeCount = 0;
int speedCount = 300;


@implementation FirstViewController
@synthesize start;
@synthesize locManager;
@synthesize lastAccurateLocation;
@synthesize reportString;
@synthesize lock;
@synthesize speedStr;
@synthesize distanceStr;
@synthesize startButton,pauseButton;
@synthesize timer,pauseDate;
@synthesize findGPSView;

#pragma mark - View Cycles
- (void)dealloc {
	[startButton release];
	[pauseButton release];
	[speedStr release];
	[distanceStr release];
	[locManager release];
    [super dealloc];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    [locateInfo release];
}

-(void)viewWillAppear:(BOOL)animated {

	[super viewWillAppear:YES];
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(findGPS:) 
												 name:@"LocationManagerFailed" 
											   object:nil];
}
-(id)init {

	if (self = [super init]) {
		self.view.backgroundColor = [UIColor blackColor];
		self.navigationItem.title = @"New Ride";

		timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 40, 300, 100)];
		timeLabel.font = [UIFont fontWithName:@"DBLCDTempBlack" size:50];
		timeLabel.text = @"00:00:00";
		timeLabel.textAlignment = UITextAlignmentCenter;
		timeLabel.textColor = [UIColor whiteColor];
		timeLabel.layer.cornerRadius = 8;
		timeLabel.backgroundColor = [UIColor colorWithRed:0.14 green:0.14 blue:0.14 alpha:1.0f];
		[self.view addSubview:timeLabel];
		[timeLabel release];
		
		self.startButton = [UIButton buttonWithType:UIButtonTypeCustom];
		startButton.frame = CGRectMake(100, 250, 128, 128);
		[startButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
		[startButton addTarget:self action:@selector(startUpdate:) forControlEvents:UIControlEventTouchUpInside];
		[self.view addSubview:startButton];
		
		self.pauseButton = [UIButton buttonWithType:UIButtonTypeCustom];
		pauseButton.frame = CGRectMake(100, 250, 128, 128);
		pauseButton.alpha = 0;
		[pauseButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
		[pauseButton addTarget:self action:@selector(stopCounting) forControlEvents:UIControlEventTouchUpInside];
		[self.view addSubview:pauseButton];
		
		UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 160, 300, 80)];
		label.layer.cornerRadius = 8;
		label.backgroundColor = [UIColor colorWithRed:0.28 green:0.28 blue:0.28 alpha:1.0f];
		[self.view addSubview:label];
		[label release];
		
		
		
		distanceLael = [[UILabel alloc]initWithFrame:CGRectMake(25, 4, 150, 50)];
		distanceLael.backgroundColor = [UIColor clearColor];
		distanceLael.textColor = [UIColor whiteColor];
		distanceLael.font = [UIFont systemFontOfSize:30];
		distanceLael.text = @"0.0 km";
		[label addSubview:distanceLael];
		[distanceLael release];
		
		UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(90, 57, 50, 20)];
		label1.text = @"距离";
		label1.backgroundColor = [UIColor clearColor];
		label1.textColor = [UIColor whiteColor];
		[label addSubview:label1];
		[label1 release];
		
		speedLabel = [[UILabel alloc]initWithFrame:CGRectMake(175, 4, 130, 50)];
		speedLabel.backgroundColor = [UIColor clearColor];
		speedLabel.textColor = [UIColor whiteColor];
		speedLabel.font = [UIFont systemFontOfSize:30];
		speedLabel.text = @"0.0 mph";
		[label addSubview:speedLabel];
		[speedLabel release];
		
		UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(240, 57, 50, 20)];
		label2.text = @"速度";
		label2.backgroundColor = [UIColor clearColor];
		label2.textColor = [UIColor whiteColor];
		[label addSubview:label2];
		[label2 release];
		
//		lock = [[UIBarButtonItem alloc]initWithTitle:@"锁屏" style:UIBarButtonItemStylePlain target:self action:nil];
//		self.navigationItem.rightBarButtonItem = lock;
//		[lock release];
		
		locateInfo = [[NSMutableArray alloc]init];
		
		self.findGPSView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 440)];
		findGPSView.backgroundColor = [UIColor colorWithRed:0.80 green:0.80 blue:0.80 alpha:0.7];
		
		UIButton *search = [UIButton buttonWithType:UIButtonTypeRoundedRect];
		[search setTitle:@"search" forState:UIControlStateNormal];
		[search addTarget:self action:@selector(findGPS) forControlEvents:UIControlEventTouchUpInside];
		search.frame = CGRectMake(100, 200, 120, 50);
		
		[findGPSView addSubview:search];
		
	}
	return self;
}



// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	[super loadView];
	
	isCounting = NO;
	
	signalLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 150, 30)];
	signalLabel.backgroundColor = [UIColor clearColor];
	signalLabel.textColor = [UIColor whiteColor];
	[self.view addSubview:signalLabel];
	[signalLabel release];
	
		
	self.locManager = [[[CLLocationManager alloc] init] autorelease];
	
	if ([CLLocationManager locationServicesEnabled])
	{
		signalLabel.text = @"GPS signal OK";
	}


	
	self.locManager.delegate = self;
	self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
	
	[self.locManager startUpdatingLocation];
	//pauseInterval  = 0;
	//[NSNotification not];
	
	//[self findGPS];
	[[NSNotificationCenter defaultCenter]addObserver:self 
											selector:@selector(updateLocationFail) 
												name:@"updateLoactionFail" 
											  object:nil];
	[[NSNotificationCenter defaultCenter]addObserver:self 
											selector:@selector(updateLocationSuccess) 
												name:@"updateLocationSuccess" 
											  object:nil];
}

#pragma mark -Actions 

-(void)updateLocationFail {

	[self.view addSubview:self.findGPSView];
	[self.locManager stopUpdatingLocation];
	signalLabel.text = @"No GPS Signal !";
}

-(void)updateLocationSuccess {

	[self.findGPSView removeFromSuperview];
	signalLabel.text = @"GPS Signal Ok !";
}

-(void)startUpdate:(id)sender {
	
	isCounting = YES;
	aggregateDistance = 0.0;
	[self.locManager startUpdatingLocation];
	self.startButton.alpha = 0;
	self.pauseButton.alpha = 1;
	self.start = [NSDate date];	
	self.pauseDate = 0;
	self.timer = [NSTimer scheduledTimerWithTimeInterval:(1.0)target:self selector:@selector(onTimer) userInfo:nil repeats:YES];	
	
	
}

-(void) onTimer
{
	NSDate* now = [NSDate date];
	reduce = [now timeIntervalSinceDate:start];
	[self updateLabel];
}

-(void)onTimerMore {
	NSDate* now = [NSDate date];
	reduce = [now timeIntervalSinceDate:start] - pauseInterval;
	[self updateLabel];
}

-(void) updateLabel
{

	//NSLog(@"%f",reduce);
	int seconds = (int)reduce % 60;
    int minutes = ((int)reduce / 60) % 60;
    int hours = (int)reduce / 3600;
	
	timeLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes,seconds];
	
	if (timeCount == speedCount) {
		[self performSelector:@selector(updateWalkInfo)];
		timeCount = 0;
	}
	
	timeCount++;
}

-(void)updateWalkInfo {

	distanceLael.text = self.distanceStr;
	speedLabel.text = self.speedStr;
	float x = [self.speedStr floatValue];
	speedCount = (int) 3600 / x;
	Coordinate *locate = [[Coordinate alloc]init];
	locate.longitude = [NSString stringWithFormat:@"%f",self.lastAccurateLocation.coordinate.longitude];
	locate.latitude = [NSString stringWithFormat:@"%f",self.lastAccurateLocation.coordinate.latitude];
	
	[locateInfo addObject:locate];
	[locate release];
}

-(void)stopCounting {
	
	[timer invalidate];
	self.pauseDate = [NSDate date];
	UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil
												 delegate:self
												 cancelButtonTitle:nil
												 destructiveButtonTitle:@"Discard Ride" otherButtonTitles:@"End ride",@"Resume Ride",nil];
	[sheet showFromTabBar:self.tabBarController.tabBar];
	
}

-(void)saveRide {
	[self performSelector:@selector(updateWalkInfo)];
	
	WalkInfo *info = [[WalkInfo alloc]init];
	
	NSDate *now = [NSDate date];
	NSString *time = [now description];
	//NSLog(@"time = %@",time);
	info.walkDate = time;
	info.walkCity = localString;
	info.avgSpeed = self.speedStr;
	info.distance = self.distanceStr;
	info.walkCount = [NSString stringWithFormat:@"%d",(int)reduce];
	info.locateArray = locateInfo;
	
	NSMutableArray *array = [infoMgr getData];
	NSMutableArray *data = [[NSMutableArray alloc]init];
	[data addObjectsFromArray:array];
	[data addObject:info];
	[infoMgr saveData:data];
	
	DogLocateAppDelegate *delegate = (DogLocateAppDelegate *)[[UIApplication sharedApplication] delegate];
	delegate.tabVC.selectedIndex = 1;

	
	[self performSelector:@selector(initCounting)];
	//InfoMgr *infoManager = [[InfoMgr alloc]init];
}

-(void)keepGoOn {
	NSDate *now = [NSDate date];
	pauseInterval = [now timeIntervalSinceDate:pauseDate] + pauseInterval;

	self.timer = [NSTimer scheduledTimerWithTimeInterval:(1.0)target:self selector:@selector(onTimerMore) userInfo:nil repeats:YES];	

}
-(void)initCounting {

	timeLabel.text = @"00:00:00";
	distanceLael.text = @"0.0 km";
	speedLabel.text = @"0.0 mph";
	aggregateDistance = 0.0;
	
	self.pauseButton.alpha = 0;
	self.startButton.alpha = 1;
	
}

-(void)findGPS {
//	[[NSNotificationCenter defaultCenter] removeObserver:self 
//													name:@"LocationManagerFailed" 
//												  object:nil];
	[self.locManager startUpdatingLocation];
	
	//[self.findGPSView removeFromSuperview];
}

//-(void)searchGPS {
//
//	UIView *v = [self.view viewWithTag:100];
//	//UIButton *button = (UIButton *)[self.view viewWithTag:101];
//	UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 200, 120, 30)];
//	label.text = @"正在搜寻";
//	[v addSubview:label];
//	[label release];
//	
//	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(findGPSResult) name:@"fingGPSResult" object:nil];
//}
#pragma mark ACtionSheet delegate 

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == 0) {
		[self performSelector:@selector(initCounting)];
	}else if (buttonIndex == 1) {
		[self performSelector:@selector(saveRide)];
	}else if (buttonIndex == 2) {
		[self performSelector:@selector(keepGoOn)];
	}
}

#pragma mark CLLocationManager delegate

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
//	[[NSNotificationCenter defaultCenter] addObserver:self
//											 selector:@selector(findGPS:)
//												 name:@"LocationManagerFailed" object:nil];
	[[NSNotificationCenter defaultCenter] 
					postNotificationName:@"updateLocationFail" 
					object:nil];

	NSLog(@"error : %@",[error description]);
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
	[[NSNotificationCenter defaultCenter] 
	 postNotificationName:@"updateLocationSuccess" 
	 object:nil];
	
	CLLocationCoordinate2D coordinate2D;
	coordinate2D.longitude = newLocation.coordinate.longitude;
	coordinate2D.latitude = newLocation.coordinate.latitude;
	MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:coordinate2D];
	geoCoder.delegate = self;
	[geoCoder start];
	
	if (newLocation.horizontalAccuracy < kCLLocationAccuracyHundredMeters) // within 300 feet or so
	{
		if (self.lastAccurateLocation)
		{
			NSTimeInterval dTime = [newLocation.timestamp timeIntervalSinceDate:self.lastAccurateLocation.timestamp];
			float distance = [newLocation distanceFromLocation:lastAccurateLocation];
			if (distance < 1.0f) 
				return;
			
			aggregateDistance += distance;
			//self.reportString = [NSString stringWithFormat:@"Speed: %0.1f miles per hour. Distance: %0.1f meters.", 2.23693629 * distance / dTime, aggregateDistance];
			//[self report: reportString];
			//[self doLog: reportString];
			self.speedStr = [NSString stringWithFormat:@"%0.1f mph",2.23693629 * distance / dTime];
			self.distanceStr = [NSString stringWithFormat:@"%0.1f km",aggregateDistance / 1000];
			
		}
		
		self.lastAccurateLocation = newLocation;
		
	}

}

#pragma mark -Get city code

//- (void)startedReverseGeoderWithLatitude:(double)latitude longitude:(double)longitude{
//	CLLocationCoordinate2D coordinate2D;
//	coordinate2D.longitude = longitude;
//	coordinate2D.latitude = latitude;
//	MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:coordinate2D];
//	geoCoder.delegate = self;
//	[geoCoder start];
//}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
    localString = placemark.locality;
	
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
}


#pragma mark Lock Screen

- (void)lockScren {
	
	SlideToCancelViewController *v = [[SlideToCancelViewController alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
	//v.frame = CGRectMake(0, 0, 320, 480);
	[self.view addSubview:v];
	[v release];
}

// SlideToCancelDelegate method is called when the slider is slid all the way
// to the right
- (void) cancelled {
//	// Disable the slider and re-enable the button
//	slideToCancel.enabled = NO;
//	lock.enabled = YES;
//	
//	// Slowly move down the slider off the bottom of the screen
//	[UIView beginAnimations:nil context:nil];
//	[UIView setAnimationDuration:0.5];
//	CGPoint sliderCenter = slideToCancel.view.center;
//	sliderCenter.y += slideToCancel.view.bounds.size.height;
//	slideToCancel.view.center = sliderCenter;
//	[UIView commitAnimations];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}






@end
